/*******************************************************************************
 * Copyright (c) 2007 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Matt Carter - Character support completed (bug 197679)
 *     Tran Nhut Trung - Support GWT
 ******************************************************************************/
package org.eclipse.core.databinding;


import org.eclipse.core.databinding.conversion.IConverter;
import org.eclipse.core.databinding.conversion.gwt.Converters;


public class GWTUpdateValueStrategy extends UpdateValueStrategy {
  private static Class autoboxed(Class clazz) {
    if (clazz == float.class)
      return Float.class;
    else if (clazz == double.class)
      return Double.class;
    else if (clazz == short.class)
      return Short.class;
    else if (clazz == int.class)
      return Integer.class;
    else if (clazz == long.class)
      return Long.class;
    else if (clazz == byte.class)
      return Byte.class;
    else if (clazz == boolean.class)
      return Boolean.class;
    else if (clazz == char.class)
      return Character.class;
    return clazz;
  }
  
  private Object pattern;
  
  public GWTUpdateValueStrategy() {
  }
  public GWTUpdateValueStrategy(Object pattern) {
    this.pattern = pattern;
  }
  
  protected IConverter createConverter(Object fromType, Object toType) {
    if (!(fromType instanceof Class) || !(toType instanceof Class)) {
      return super.createConverter(fromType, toType);
    }

    Class toClass = (Class) toType;
    if (toClass.isPrimitive()) {
      toClass = autoboxed(toClass);
    }
    Class fromClass = (Class) fromType;
    if (fromClass.isPrimitive()) {
      fromClass = autoboxed(fromClass);
    }
    
    if ((fromClass == toClass) && (pattern == null)){
      return new DefaultConverter(fromType, toType);
    }
    IConverter converter = Converters.getConverter(fromClass, toClass, pattern);
    if (converter != null){
      return converter;
    }
    
    return super.createConverter(fromType, toType);
  }
}
